﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Asn1.Ocsp;
using SlaughterItem.API.Application.Commands.Week01.ManageCommands.Clientses;
using SlaughterItem.API.Application.Commands.Week02.Leo;
using SlaughterItem.API.Application.Commands.Week03.leo;
using SlaughterItem.API.Application.Commands.Week03.wenk;
using SlaughterItem.Common.Domains.Manages;
using SlaughterItem.Common.Domains.Saleser;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Common.Infrastructures.Repositories;
using SlaughterItem.Enum;
using System.Globalization;

namespace SlaughterItem.API.Controllers.Leo
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WorkList01_leo : ControllerBase
    {
        private readonly IMediator mediator;
        //销售明细表
        private readonly IBaseRepository<SalesDetails> SalesDetails;
        //客户名称表
        private readonly IBaseRepository<Clients> Clients;

        private readonly ILogger<WorkList01_leo> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator"></param>
        public WorkList01_leo(IMediator mediator, IBaseRepository<SalesDetails> SalesDetails, IBaseRepository<Clients> Clients, ILogger<WorkList01_leo> logger)
        {
            this.mediator = mediator;
            this.SalesDetails = SalesDetails;
            this.Clients = Clients;
            this.logger = logger;
        }

        /// <summary>
        /// 客户删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetClientsDel(ClientsDeleteCommend cmd)
        {
            try
            {
                logger.LogInformation("客户删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("客户删除失败");
                throw;
            }
            
        }

        /// <summary>
        /// 待宰管理添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSlaugAdd(SlaughteredCreaetCommend cmd)
        {
            try
            {
                logger.LogInformation("待宰管理添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("待宰管理添加失败");
                throw;
            }
            
        }

        /// <summary>
        /// 待宰圈管理删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSlaugDel(SlaughteredDeleteCommend cmd)
        {
            try
            {
                logger.LogInformation("待宰圈管理删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("待宰圈管理删除失败");
                throw;
            }
            
        }

        /// <summary>
        /// 待宰圈管理修改
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSlaugUpdate(SlaughteredUpdateCommend cmd)
        {
            try
            {
                logger.LogInformation("待宰圈管理修改成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("待宰圈管理修改失败");
                throw;
            }
            
        }

        /// <summary>
        /// 磅秤类型添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetScaleAdd(ScaleTypeCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("磅秤类型添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("磅秤类型添加失败");
                throw;
            }
            
        }

        /// <summary>
        /// 皮重设置添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetTareAdd(TareCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("皮重设置添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("皮重设置添加失败");
                throw;
            }
           
        }

        /// <summary>
        /// 分割领用添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSplitRequisAdd(SplitRequisCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("分割领用添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("分割领用添加失败");
                throw;
            }
            
        }

        /// <summary>
        /// 分割领用删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSplitRequisDel(SplitRequisDeleteCommend cmd)
        {
            try
            {
                logger.LogInformation("分割领用删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("分割领用删除失败");
                throw;
            }
           
        }

        /// <summary>
        /// 分割领用修改
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSplitRequisUpdate(SplitRequisUpdateCommend cmd)
        {
            try
            {
                logger.LogInformation("分割领用修改成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("分割领用修改失败");
                throw;
            }
            
        }

        /// <summary>
        /// 销售称重添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSaleAdd(SaleCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("销售称重添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("销售称重添加失败");
                throw;
            }
            
        }

        /// <summary>
        /// 销售称重删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSaleDelete(SaleDeleteCommend cmd)
        {
            try
            {
                logger.LogInformation("销售称重删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("销售称重删除失败");
                throw;
            }
            
        }

        /// <summary>
        /// 销售明细
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSaleDetaisAdd(SaleDetaisCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("销售明细成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("销售明细失败");
                throw;
            }
            
        }

        /// <summary>
        /// 销售明细删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetSaleDetaisDel(SaleDetaisDelCommend cmd)
        {
            try
            {
                logger.LogInformation("销售明细删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("销售明细删除失败");
                throw;
            }
           
        }


        /// <summary>
        /// 销售明细导入
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        //[HttpPost]
        //public dynamic GetImport(IFormFile file)
        //{
        //    var result = new Result() { Code = (int)CommonErrorCode.Search };
        //    //获取文件扩展名 判断上传的文件类型是否正确
        //    var ext = Path.GetExtension(file.FileName);
        //    if (ext == ".xls" || ext == ".xlsx")
        //    {

        //    }
        //    else
        //    {
        //        return "您上传的文件类型不正确";
        //    }

        //    using (MemoryStream ms = new MemoryStream())
        //    {
        //        file.CopyTo(ms);
        //        ms.Position = 0;

        //        //根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls，XSSFWorkbook用于.xlsx)
        //        //获取工作簿
        //        IWorkbook wb = null;
        //        if (ext == ".xls")//创建97-2003
        //        {
        //            wb = new HSSFWorkbook(ms);
        //        }
        //        else//创建2007及以上版本
        //        {
        //            wb = new XSSFWorkbook(ms);
        //        }

        //        //获取sheet 获取工作簿中的第一个工作表
        //        ISheet sheet = wb.GetSheetAt(0);

        //        int totalRows = sheet.LastRowNum;//总行数
        //        int totalCells = sheet.GetRow(0).LastCellNum;//总列数

        //        // 创建一个用于存储解析后的数据的列表
        //        var farrowingsList = new List<SalesDetails>();

        //        //循环总行数 开头必须是1 不然从表头开始
        //        //遍历工作表的每一行（从第二行开始，因为第一行通常是表头）
        //        for (int i = 1; i <= totalCells; i++)
        //        {
        //            //获取当前行
        //            IRow row = sheet.GetRow(i);

        //            //这个类必须写到循环里边 不然你批量添加只能添加一行
        //            var dto = new SalesDetails();// 在循环内创建新的对象实例

        //            ////下标从0开始 导入时 外键需进行判断 客户不知道你是外键 只会输入文字 需要在后台判断
        //            //var earnumber = row.GetCell(0).ToString();
        //            //var basic = SalesDetails.GetAll().Where(z => z.SalesDetailsOrderNum == earnumber).FirstOrDefault();
        //            //dto.CustomerId = basic.CustomerId;

        //            //日期转换
        //            //日期在excel表中必须是年月日格式 但不能加时分秒 (注意!!!!)
        //            string inputDate = row.GetCell(1).ToString();
        //            string[] multipleFormats = { "dd-M月-yyyy", "yyyy-M-dd" };
        //            DateTime parsedDate;
        //            foreach (var format in multipleFormats)
        //            {
        //                if (DateTime.TryParseExact(inputDate, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
        //                {
        //                    dto.SalesDetailsDate = Convert.ToDateTime(parsedDate.ToString("yyyy-MM-dd"));
        //                    break;//成功解析后跳出循环
        //                }
        //            }

        //            dto.CustomerId = Convert.ToInt32(row.GetCell(2).ToString());
        //            dto.SalesDetailsOrderNumber = row.GetCell(3).ToString();
        //            dto.SalesDetailsOrderNum = row.GetCell(4).ToString();
        //            dto.SalesDetailsState = Convert.ToBoolean(row.GetCell(5).ToString() == "已发货" ? 1 : 0);

        //            //添加到数据集合中
        //            farrowingsList.Add(dto);
        //        }
        //        //跳出循环后 使用AddRange进行批量添加
        //        var res = SalesDetails.AddRange(farrowingsList);
        //        //判断
        //        if (res > 0)
        //        {
        //            result.Msg = "导入成功";
        //        }
        //        else
        //        {
        //            result.Msg = "导入失败";
        //        }

        //        return result;
        //    }
        //}


        /// <summary>
        /// 膘油称重添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOilyfatAdd(OilyfatCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("膘油称重添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("膘油称重添加失败");
                throw;
            }
        }

        /// <summary>
        /// 膘油称重删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOilyfatDel(OilyfatDelCommend cmd)
        {
            try
            {
                logger.LogInformation("膘油称重删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("膘油称重删除失败");
                throw;
            }
        }

        /// <summary>
        /// 生产划膘单添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetScratchesAdd(ScratchesCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("生产划膘单添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("生产划膘单添加失败");
                throw;
            }
        }

        /// <summary>
        /// 生产划膘单删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetScratchesDel(ScratchesDelCommend cmd)
        {
            try
            {
                logger.LogInformation("生产划膘单删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("生产划膘单删除失败");
                throw;
            }
        }

    }
}
